package com.ibeifeng.crm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ibeifeng.crm.bean.Salesman;
import com.ibeifeng.crm.service.SalesmanService;
import com.ibeifeng.crm.util.LogMessage;

@Controller
@RequestMapping("/pages/salesman/")
public class SalesmanController {
	@Resource
	LogMessage logMessage;
	@Resource
	SalesmanService salesmanService;
	@RequestMapping(value = "mquery", produces = { "application/json;charset=UTF-8" })
	public @ResponseBody String mquery(HttpServletRequest request, HttpServletResponse response){
		String pg = request.getParameter("page");
		String pgSize = request.getParameter("rows");
		String keyWord=request.getParameter("keyWord");
		// 若要显示的第几页为空，那么默认为1
		if (null == pg || "".equals(pg)) {
			pg = "1";
		}
		// 显示多少行为空，那么默认为10
		if (null == pgSize || "".equals(pgSize)) {
			pgSize = "5";
		}		
		List<Salesman> salesman = salesmanService.mquery(Integer.parseInt(pg), Integer.parseInt(pgSize),keyWord);
		int count=salesmanService.count();
		// 将从后台获得的classroom对象列表，以及总共查询多少个符合条件下的记录个数，以Map格式传到前台
		Map map = new HashMap();
		if(count>0){
		map.put("total", count);
		}else{
			map.put("total", 1);
		}
		map.put("rows", salesman);
		JSONArray obj = JSONArray.fromObject(map);
		String str = obj.toString();
		String js = str.substring(1, str.length() - 1);
		return js;
	}
	@RequestMapping("add")
	public @ResponseBody String add(Salesman sm){
		boolean add = salesmanService.add(sm);
		JSONObject jsonObject  = new JSONObject();
		if(add){
			jsonObject.put("result","true");
		}else{
			jsonObject.put("msg","save error");
		}
		return jsonObject.toString();
	}
	@RequestMapping("delete")
	public @ResponseBody String delete(HttpServletRequest request, HttpServletResponse response){
		String[] array = request.getParameterValues("array[]");  
		List<Integer> list = new ArrayList<Integer>();  
		for (int i = 0; i < array.length; i++) {  
			int id = Integer.parseInt(array[i]);
		list.add(id);  
		}		
		boolean b = salesmanService.delete(list);
		JSONObject jsonObject  = new JSONObject();
		if(b){
			jsonObject.put("result","true");
		}else{
			jsonObject.put("msg","save error");
		}
		return jsonObject.toString();
	}
	@RequestMapping("update")
	public @ResponseBody String update(Salesman sm){
		boolean b = salesmanService.update(sm);
		JSONObject jsonObject  = new JSONObject();
		if(b){
			jsonObject.put("result","true");
		}else{
			jsonObject.put("msg","save error");
		}
		return jsonObject.toString();
	}
}
